package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ZCF
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.stringRedisTemplate= redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.获取请求头中的token
        String token = request.getHeader("authorization");
        //2.判断token
        if (StrUtil.isBlank(token)) {
            //放行到下一拦截器
            return true;
        }
        //3.根据token判断用户是否存在
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        //对于容器来说，null是判断有没有这个容器，isEmpty()是判断容器有没有内容
        if (entries.isEmpty()) {
            return true;
        }
        //4.将map转化为user对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        //5.保存在ThreadLocal
        UserHolder.saveUser(userDTO);
        //6.刷新token的有效期
      stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,5, TimeUnit.MINUTES);
        //7.放行
        return true;
    }


    /**
     * 请求处理完，视图渲染后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
